<style lang="scss" scoped></style>

<template>
  <v-layout class="flex-column overflow-y-hidden" style="height: 100vh">
    <div class="d-flex align-center pa-2">
      <h2 style="width: 140px">写博客</h2>
      <h2 style="width: 140px">文章标题:</h2>
      <v-text-field
        v-model="title"
        append-inner-icon="mdi-map-marker"
        hide-details
        class="flex-1-1 neu-input"
        variant="solo"
        placeholder="请输入标题"
      ></v-text-field>
      <a
        style="width: 120px"
        class="text-center"
        target="_blank"
        href="https://imzbf.github.io/md-editor-v3/zh-CN/syntax"
        >编辑器语法</a
      >
    </div>
    <md-editor
      showToolbarName
      class="flex-fill"
      v-model="text"
      @onUploadImg="
        (files) => {
          console.log(files)
        }
      "
      @onSave="onSave"
      @transformImgUrl="transformImageUrl"
      @onDrop="onDrop"
      @onHtmlChanged="(html) => {}"
      @onGetCatalog="
        (catalog) => {
          console.log(catalog)
        }
      "
    />

    <v-footer class="d-flex align-center justify-end ga-2 flex-0-1" height="64px">
      <v-btn color="pink-lighten-1" rounded>存草稿</v-btn>
      <v-btn color="light-blue-lighten-1" rounded>发布</v-btn>
    </v-footer>
  </v-layout>
</template>

<script lang="ts" setup>
import { ref, defineComponent, onUnmounted, onMounted } from 'vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
const isSaved = ref(false)
defineComponent({
  components: { MdEditor }
})

onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload)
})
const handleBeforeUnload = function (event: Event) {
  event.preventDefault()
  // 给出一个提示信息，告知用户有未保存的数据或者询问用户是否真的想离开页面
  const message = '您有未保存的更改，确定要离开吗？'
  event.returnValue = true // 标准写法，用于大多数现代浏览器
  // 对于一些旧版浏览器，返回字符串作为提示信息
  return message
}
onUnmounted(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
const text = ref('')
const title = ref('')
const transformImageUrl = (t: string) => {
  console.log(t)
  return ''
}

const onSave = (v: string, h: Promise<string>) => {
  console.log(v)
  isSaved.value = true
  h.then((html: string) => {
    console.log(html)
  })
}

// 拖动到编辑器
const onDrop = (e: DragEvent) => {
  e.stopPropagation()
  console.log('ee', e.dataTransfer?.files[0])
}

// 服务端验证，安全
const validate_markdown = (content: string) => {
  // 检查内容长度
  if (content.length > 65535) {
    return '太长'
  }

  // 检查恶意模式
  if (content.includes('<script') || content.includes('javascript:')) {
    return '存在恶意代码'
  }
}
</script>
